package com.sdap2.service.impl;

import com.sdap2.common.context.RequestContext;
import com.sdap2.common.dao.LogicDAO;
import com.sdap2.common.exception.BusinessException;
import com.sdap2.common.service.impl.BaseService;
import com.sdap2.common.utils.AssertUtil;
import com.sdap2.common.utils.JwtUtil;
import com.sdap2.dao.SysUserDAO;
import com.sdap2.dto.UserLoginDTO;
import com.sdap2.dto.UserRegisterDTO;
import com.sdap2.entity.SysUser;
import com.sdap2.service.SysUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@RequiredArgsConstructor
public class SysUserServiceImpl extends BaseService<SysUser> implements SysUserService {
    
    private final SysUserDAO sysUserDAO;
    private final PasswordEncoder passwordEncoder;
    private final JwtUtil jwtUtil;

    @Override
    protected LogicDAO<SysUser, Long> getRepository() {
        return sysUserDAO;
    }

    @Override
    public String login(UserLoginDTO loginDTO) {
        SysUser user = sysUserDAO.findByUsername(loginDTO.getUsername())
                .orElseThrow(() -> new BusinessException("用户名或密码错误"));
                
        if (!passwordEncoder.matches(loginDTO.getPassword(), user.getPassword())) {
            throw new BusinessException("用户名或密码错误");
        }
        
        if (user.getStatus() == 0) {
            throw new BusinessException("账号已被禁用");
        }
        
        return jwtUtil.generateToken(user.getUsername());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void register(UserRegisterDTO registerDTO) {
        // 检查用户名是否已存在
        AssertUtil.isFalse(sysUserDAO.existsByUsername(registerDTO.getUsername()), 
            "用户名已存在");
        
        SysUser user = new SysUser();
        BeanUtils.copyProperties(registerDTO, user);
        // 加密密码
        user.setPassword(passwordEncoder.encode(registerDTO.getPassword()));
        // 设置状态为启用
        user.setStatus(1);
        
        // 保存用户
        sysUserDAO.save(user);
        
        try {
            // 关联默认角色（角色ID为1，对应普通用户角色）
            sysUserDAO.insertUserRole(user.getId(), 1L);
        } catch (Exception e) {
            throw new BusinessException("系统角色未初始化，请联系管理员");
        }
    }

    @Override
    public SysUser getCurrentUser(String token) {
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
        }
        System.out.println(token);
        if (jwtUtil.validateToken(token)) {
            String username = jwtUtil.getUsernameFromToken(token);
            System.out.println("username: "+username);
            return sysUserDAO.findByUsernameWithRoles(username).orElse(null);
        }
        return null;
    }
} 